package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file){
        //获取原始文件名并且获取后缀,拼接文件名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String name = UUID.randomUUID().toString()+substring;
        //判断文件夹是否存在
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        //转移文件至指定文件夹中
        try {
            file.transferTo(new File(path+name));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传图片失败");
        }
        return R.success(name);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //创建一个输入流读取文件
        try {
            //response.setHeader("Content-Disposition","attachment; filename="+name);// 强制要求浏览器下载。
            //response.setContentType("image/jpeg");// 告知浏览器响应的内容类型

            FileInputStream iutputStream = new FileInputStream(new File(path + File.separator+ name));
            //获取一个输出流,输出文件至浏览器页面
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(iutputStream,outputStream);
            iutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
